const BasePlugin = require('./base-plugin');

class HonorPlugin extends BasePlugin {
    constructor() {
        super();
        this.name = '荣誉系统插件';
        this.version = '1.0.0';
        this.author = '系统';
        this.priority = 2; // 高优先级
        this.description = '群荣誉和头衔管理功能';
        this.honorCounts = new Map(); // 记录荣誉次数
    }

    /**
     * 处理群荣誉变更事件
     */
    onGroupHonorChange(event, reply) {
        const { group_id, user_id, honor_type } = event;
        
        const honorNames = {
            'talkative': '🏆 龙王',
            'performer': '🔥 群聊之火', 
            'emotion': '😄 快乐源泉',
            'legend': '🌟 群传奇',
            'strong_newbie': '💪 强大新人'
        };

        const honorName = honorNames[honor_type] || honor_type;
        
        // 更新荣誉计数
        const key = `${group_id}_${user_id}_${honor_type}`;
        this.honorCounts.set(key, (this.honorCounts.get(key) || 0) + 1);
        const count = this.honorCounts.get(key);

        const message = `🎉 恭喜 @${user_id} 获得${honorName} 荣誉！\n📊 这是第 ${count} 次获得此荣誉`;
        reply(message);
        
        return true;
    }

    /**
     * 处理群头衔变更事件
     */
    onGroupTitleChange(event, reply) {
        const { group_id, user_id, title_new, title_old } = event;
        
        let message;
        if (!title_old && title_new) {
            message = `👑 @${user_id} 获得了新头衔: ${title_new}`;
        } else if (title_old && !title_new) {
            message = `👑 @${user_id} 的头衔被移除: ${title_old}`;
        } else {
            message = `👑 @${user_id} 头衔变更: ${title_old} → ${title_new}`;
        }
        
        reply(message);
        return true;
    }

    /**
     * 处理群红包运气王事件
     */
    onGroupLuckyKing(event, reply) {
        const { group_id, user_id, target_id } = event;
        
        const message = `🍀 恭喜 @${user_id} 成为运气王！\n🎁 红包由 @${target_id} 发送`;
        reply(message);
        
        return true;
    }

    /**
     * 处理精华消息事件
     */
    onEssenceMessageChange(event, reply) {
        const { group_id, sender_id, operator_id, message_id, sub_type } = event;
        
        const action = sub_type === 'add' ? '设为精华消息' : '移除精华消息';
        const message = `💎 消息${action}\n发送者: @${sender_id}\n操作者: @${operator_id}`;
        
        reply(message);
        return true;
    }

    /**
     * 处理荣誉查询指令
     */
    onGroupMessage(event, reply) {
        const message = event.raw_message;
        
        if (message === '我的荣誉') {
            this.showUserHonors(event, reply);
            return true;
        }
        
        if (message === '群荣誉榜') {
            this.showGroupHonorRank(event, reply);
            return true;
        }

        if (message === '荣誉帮助') {
            const helpText = `🏆 荣誉系统帮助
• 我的荣誉 - 查看个人荣誉统计
• 群荣誉榜 - 查看群荣誉排行榜
• 自动记录龙王、群聊之火等荣誉`;
            reply(helpText);
            return true;
        }

        return false;
    }

    /**
     * 显示用户荣誉
     */
    async showUserHonors(event, reply) {
        const { group_id, user_id } = event;
        
        // 获取用户在该群的所有荣誉
        const userHonors = [];
        for (let [key, count] of this.honorCounts) {
            const [gid, uid, honor_type] = key.split('_');
            if (gid === group_id.toString() && uid === user_id.toString()) {
                userHonors.push({ type: honor_type, count });
            }
        }
        
        if (userHonors.length === 0) {
            reply('📊 您还没有获得任何群荣誉，继续加油！');
            return;
        }
        
        let message = `🏆 @${user_id} 的荣誉统计:\n`;
        userHonors.forEach(honor => {
            message += `• ${this.getHonorName(honor.type)}: ${honor.count} 次\n`;
        });
        
        reply(message);
    }

    /**
     * 显示群荣誉排行榜
     */
    async showGroupHonorRank(event, reply) {
        const { group_id } = event;
        
        // 统计群内所有用户的荣誉
        const honorStats = new Map();
        for (let [key, count] of this.honorCounts) {
            const [gid, uid, honor_type] = key.split('_');
            if (gid === group_id.toString()) {
                if (!honorStats.has(uid)) {
                    honorStats.set(uid, { total: 0, honors: {} });
                }
                const userStats = honorStats.get(uid);
                userStats.total += count;
                userStats.honors[honor_type] = count;
            }
        }
        
        if (honorStats.size === 0) {
            reply('📊 本群暂无荣誉记录');
            return;
        }
        
        // 按总荣誉数排序
        const sortedUsers = Array.from(honorStats.entries())
            .sort((a, b) => b[1].total - a[1].total)
            .slice(0, 5); // 取前5名
        
        let message = `🏆 群荣誉排行榜:\n`;
        sortedUsers.forEach(([uid, stats], index) => {
            const rankIcon = index === 0 ? '🥇' : index === 1 ? '🥈' : index === 2 ? '🥉' : '📊';
            message += `${rankIcon} @${uid}: ${stats.total} 次荣誉\n`;
        });
        
        reply(message);
    }

    getHonorName(honor_type) {
        const names = {
            'talkative': '龙王',
            'performer': '群聊之火',
            'emotion': '快乐源泉',
            'legend': '群传奇',
            'strong_newbie': '强大新人'
        };
        return names[honor_type] || honor_type;
    }
}

module.exports = HonorPlugin;